// pages/newsDetail/newsDetail.js
var app = getApp();
var util = require("../../utils/util.js")
var fake_comments = require("../../data/data_comments.js");
var getComment_url = "https://www.hkzhaoscut.top/normalUser/getCommentByNews"
var delete_url = "https://www.hkzhaoscut.top/normalUser/deleteCommentByUser"
var addComment_url = "https://www.hkzhaoscut.top/normalUser/addCommentByUser"
var thumbUp_url = "https://www.hkzhaoscut.top/normalUser/addStars"
var remove_thumbUp_url = "https://www.hkzhaoscut.top/normalUser/removeStars"
// 这是向后台获取评论信息的
var pageNum = 2
var pageSize = 5
// 这是数据库通信提交新的评论信息
var submitComment = function(token, new_id, comment) {
  console.log("token为" + token)
  wx.request({
    url: addComment_url,
    data: {
      user_token: token,
      news_id: new_id,
      text: comment
    }
  })
}

Page({
  /**
   * 页面的初始数据
   */
  data: {
    loginStauts: '', //登陆状态
    userType: '', //用户类型
    totalPage: 0, //评论页数
    userToken: '', //当前用户的
    scrollHeight: 0,
    scrollTop: 0,
    _new: [], //新闻内容
    new_id: '', //单独提取出来方便获取评论
    comment: "",
    commentList: [],
    // hideComment:[],// 用于展开评论的变量
    thumbUp: [], // 存储点赞过的commentid
    thumbDict: {}, //用字典存储是否点赞过某一评论，key存的是commentid
    cancelThumbUp: [], //取消的点赞数组
    updateThumbUp:[],//用于更新点赞的数组，是现有的与本地的thumb的差集
    preThumbUp:[], //本地点赞的数组，
  },
  // 对于回复他人的评论，采取更新的方法，更新该数组下的replyComment属性

  // 提交评论
  submit(e) {
    // 先检查登陆状态
    if ((app.globalData.userType == 'user') && app.globalData.loginStauts == true) {
      var that = this
      var comment = that.data.comment
      if (comment == "") {
        wx.showToast({
          title: '评论不能为空！',
          icon: 'none',
        })
      } else {
        // 提交评论
        console.log("评论内容为:" + comment)
        var userToken = that.data.userToken
        var news_id = that.data.new_id
        submitComment(userToken, news_id, comment)
        // 本地也需更新评论信息，需要登录后的用户id认证、名字和头像
        var newComment = {}
        var date = new Date()
        newComment.commentDate = util.formatTime(date)
        newComment.myComment = comment
        newComment.thumbUpCount = 0
        newComment.commentId = new Date().getTime()
        newComment.userToken = userToken
        var originComments = that.data.commentList
        originComments.unshift(newComment)
        that.setData({
          commentList: originComments,
          comment: ''
        })
      }
    } else {
      // 跳转到登录页面
      wx.navigateTo({
        url: '../login/login',
      })
    }

  },
  // 监听输入框
  inputComment(e) {
    this.setData({
      comment: e.detail.value
    })
  },
  // 监听页面滚动
  onPageScroll(e) {
    var that = this
    that.setData({
      scrollTop: e.scrollTop
    })
  },
  // 上拉刷新
  onPullDownRefresh() {
    var new_id = this.data.new_id
    this.load_more(new_id)
  },
  //触底拉取更多评论
  onReachBottom(e) {
    var new_id = this.data.new_id
    this.load_more(new_id)
  },

  //  点赞
  // 逻辑如下:本地缓存一个保存当前点赞评论id的数组
  // 每次进入新闻获取该数组，若点赞了新的评论，则在此数组本身增加，最后退出时求原始数组和新数组的差值来更新点赞数
  // 取消点赞时添加进取消点赞的数组，退出时直接请求后台，不用本地维护
  thumpUpComment(e) {
    if ((app.globalData.userType == 'user') && app.globalData.loginStauts == true) {
      var that = this
      // console.log(that.data.commentList)
      // console.log(e.currentTarget.dataset.commentid)
      var commentid = e.currentTarget.dataset.commentid
      var thumbUp = that.data.thumbUp
      var commentList = that.data.commentList
      var thumbDict = that.data.thumbDict
      var cancelThumbUp = that.data.cancelThumbUp
      // console.log("1",thumbUp, '2',cancelThumbUp)
      if (thumbUp.includes(commentid)) {
        thumbUp.splice(thumbUp.indexOf(commentid), 1)
        cancelThumbUp.push(commentid)
        thumbDict[commentid] = false
        for (var i = 0; i < commentList.length; i++) {
          if (commentList[i].commentId == commentid) {
            commentList[i].thumbUpCount--
          }
        }
      } else {
        // 点赞后取消点赞又点赞的情况
        if (cancelThumbUp.includes(commentid)) {
          cancelThumbUp.splice(cancelThumbUp.indexOf(commentid), 1)
        }
        thumbUp.push(commentid)
        thumbDict[commentid] = true
        for (var i = 0; i < commentList.length; i++) {
          if (commentList[i].commentId == commentid) {
            commentList[i].thumbUpCount++
          }
        }
      }
      that.setData({
        commentList: commentList,
        thumbDict: thumbDict,
        cancelThumbUp: cancelThumbUp,
        thumbUp: thumbUp,
      })
      // console.log("之前的点赞数组应该是",this.data.preThumbUp)
    } else {
      wx.navigateTo({
        url: '../login/login?navbar=' + 0,
      })
    }
  },
  //隐藏页面时更新点赞数到后台,并保留本地缓存
  onUnload() {
    var thumbUp = this.data.thumbUp
    var preThumbUp=this.data.preThumbUp
    var cancelThumbUp=this.data.cancelThumbUp
    console.log(thumbUp, this.data.userToken, "隐藏页面")
    // 最终需要更新点赞数的为两个数组的差集
    // 当前数组中与之前本地数组中不同的元素，以当前的全集
    var updateThumbUp = thumbUp.filter(function (v) { return preThumbUp.indexOf(v) === -1 })
    console.log("需要更新的点赞为",updateThumbUp,'之前的点赞数组',preThumbUp)
    if (updateThumbUp.length != 0) {
      var userToken = this.data.userToken
      wx.request({
        url: thumbUp_url,
        method: "POST",
        data: {
          'comment_id[]': updateThumbUp,
          'user_token': userToken
        },
        success(res) {
          console.log(res)
        }
      })
    }
    if (cancelThumbUp.length != 0) {
      var userToken = this.data.userToken
      wx.request({
        url: remove_thumbUp_url,
        method: "POST",
        data: {
          'comment_id[]': cancelThumbUp,
          'user_token': userToken
        },
        success(res) {
          console.log(res)
        }
      })
    }
    // 缓存到本地
    wx.setStorageSync("thumbUpInfo", thumbUp)
  },

  // 展开该评论所有的回复
  // commentDetail(e) {
  //   var index = e.currentTarget.dataset.idx
  //   var that = this
  //   // console.log(index)
  //   var hideComment = !that.data.hideComment[index]
  //   var setHideComment = 'hideComment[' + index + ']'
  //   that.setData({
  //     [setHideComment]: hideComment
  //   })

  // },
  // 举报
  showJubao() {
    wx.showModal({
      title: '举报',
      content: '确定举报该评论吗？',
      success: function(res) {
        if (res.confirm) {
          wx.showToast({
            title: '感谢你的反馈！',
            icon: 'none',
          })
        }
      }
    })
  },
  // 删除评论
  deleteComment(e) {
    console.log(e)
    var commentId = e.currentTarget.dataset.commentid
    var userToken = e.currentTarget.dataset.userToken
    var that = this
    wx.showModal({
      title: '删除',
      content: '确定删除该评论吗？',
      success: function(res) {
        if (res.confirm) {
          wx.request({
            url: delete_url,
            data: {
              Comment_id: commentId,
              user_token: that.data.userToken
            },
            success(res) {
              var arr = that.data.commentList
              var index = arr.findIndex((item) =>
                item.commentId == commentId
              )
              // console.log("评论index为",index)
              arr.splice(index, 1)
              that.setData({
                commentList: arr
              })
            }
          })
        }
      }
    })
  },
  //获取初始评论
  init_comments(new_id) {
    // console.log(this.data)
    var that = this
    wx.request({
      url: getComment_url,
      method: "get",
      data: {
        pageNum: 1,
        pageSize: pageSize,
        news_id: new_id
      },
      success(res) {
        console.log(res.data.data.list)
        var totalPage = res.data.data.totalPage
        var code = res.data.code
        var list = res.data.data.list
        var tmplist = []
        if (code == 200) {
          if (list.length != 0) {
            list.forEach(
              function(item, index) {
                tmplist[index] = {}
                var date = new Date(item.timestamp)
                tmplist[index].commentDate = util.formatTime(date)
                tmplist[index].myComment = item.text
                tmplist[index].thumbUpCount = item.stars
                tmplist[index].commentId = item.commentId
                tmplist[index].userToken = item.userToken
              }
            )
            var curComments = tmplist
            that.setData({
              commentList: curComments,
              totalPage: totalPage
            })
          }
          that.initThumbUp()
        }
      },
      fail(err) {
        wx.showToast({
          title: '网络错误，评论加载失败！',
          icon: 'none'
        })
      }
    })
  },
  //获取更多评论
  load_more(new_id) {
    var that = this
    if (pageNum > that.data.totalPage) {
      wx.showToast({
        title: '没有更多了！',
        icon: 'none'
      }, 300)
    } else {
      wx.showLoading({
        title: "加载中",
      }, 500)
      wx.request({
        url: getComment_url,
        data: {
          pageNum: pageNum,
          pageSize: pageSize,
          news_id: new_id
        },
        success: function(res) {
          wx.hideLoading();
          console.log(res.data.data.list)
          var code = res.data.code
          var list = res.data.data.list
          var tmplist = []
          if (code == 200) {
            if (list.length != 0) {
              console.log(pageNum)
              pageNum++;
              list.forEach(
                function(item, index) {
                  tmplist[index] = {}
                  var date = new Date(item.timestamp)
                  tmplist[index].commentDate = util.formatTime(date)
                  tmplist[index].myComment = item.text
                  tmplist[index].thumbUpCount = item.stars
                  tmplist[index].commentId = item.commentId
                  tmplist[index].userToken = item.userToken
                }
              )
              var originComments = that.data.commentList
              var curComments = originComments.concat(tmplist)
              that.setData({
                commentList: curComments

              })
            }
            that.initThumbUp()

          }

        }
      });
    }
  },
  // 进入新闻详情时初始化点赞信息
  initThumbUp() {
    if (this.data.userType=='user'){
    var thumbUp = this.data.preThumbUp
    var commentList = this.data.commentList
    var thumbDict = this.data.thumbDict
    for (var i = 0; i < commentList.length; i++) {
      // console.log("评论列表", commentList[i])
      var commentId = commentList[i].commentId
      if (thumbUp.includes(commentId)) {
        if (thumbDict[commentId] != true) {
          thumbDict[commentId] = true
          commentList[i].thumbUpCount += 1
        }
      }
    }
    this.setData({
      thumbDict: thumbDict,
      commentList: commentList
    })}
  },

  onReady(e) {
    var that = this
    wx.createSelectorQuery().select("#news-detail").boundingClientRect(function(e) {
      that.setData({
        scrollHeight: e.height
      })
    }).exec()
  },
  onShow(){
    this.setData({
      loginStauts: app.globalData.loginStauts,
      userType: app.globalData.userType,
      userToken: app.globalData.userToken,
      // hideComment: hideComment,
    })
  },
  onLoad(e) {
    var item = JSON.parse(e.item)
    var new_id = item.newsId
    console.log("新闻信息为",item,"登录角色为",app.globalData.userType)
    var that = this
    // var hideComment = new Array(1000)
    // for (var index = 0; index < 1000; index++) {
    //   hideComment[index] = true
    // }
    if (wx.getStorageSync("thumbUpInfo")!=''){
      console.log(wx.getStorageSync("thumbUpInfo"))
      var thumbUp1 = wx.getStorageSync("thumbUpInfo")
      var thumbUp2 = wx.getStorageSync("thumbUpInfo")
    }else{
      var thumbUp1=[]
      var thumbUp2 = []
    }
    
    that.setData({
      thumbUp: thumbUp1,
      preThumbUp: thumbUp2,
      new_id: new_id,
      _new: item,
      loginStauts: app.globalData.loginStauts,
      userType: app.globalData.userType, 
      userToken: app.globalData.userToken,
      // hideComment: hideComment,
    })
    pageNum = 2
    this.init_comments(new_id)

  },
})